

export const defaultX = 30;
export const defaultY = 30;
export const MIN_WIDTH = 100;
export const MIN_FONTSIZE = 200;

export const dragGraph = function ({
	x = defaultX,
	y = defaultX,
	w,
	h,
	type,
	text,
	fontSize = 20,
	color = 'red',
	url = null,
	rotate = 0,
	sourceId = null,
	selected = true,
	minWidth =MIN_WIDTH
}, canvas, factor ) {
    this.centerX = x + w / 2;
    this.centerY = y + h / 2;
    this.w = w;
    this.h = h;

	this.x = x;
	this.y = y; // 4个顶点坐标

	this.square = [[this.x, this.y], [this.x + this.w, this.y], [this.x + this.w, this.y + this.h], [this.x, this.y + this.h]];
	this.fileUrl = url;
	this.text = text;
	this.fontSize = fontSize;
	this.color = color;
	this.ctx = canvas;
	this.rotate = rotate;
	this.type = type;
	this.selected = selected;
	this.factor = factor;
	this.sourceId = sourceId;
	this.MIN_WIDTH = minWidth;
	this.MIN_FONTSIZE = MIN_FONTSIZE;
};

dragGraph.prototype = {
	paint() {
		this.ctx.save(); // 由于measureText获取文字宽度依赖于样式，所以如果是文字元素需要先设置样式

		let textWidth = 0;
		let textHeight = 0;


		this.ctx.translate(this.centerX, this.centerY);
		this.ctx.rotate(this.rotate * Math.PI / 180);
		this.ctx.translate(-this.centerX, -this.centerY); // 渲染元素

		if (this.type === 'image') {
			this.ctx.drawImage(this.fileUrl, this.x, this.y, this.w, this.h);
		};

		this.ctx.restore();
	},

	/**
	 * 计算旋转后的新坐标（相对于画布）
	 * @param x
	 * @param y
	 * @param centerX
	 * @param centerY
	 * @param degrees
	 * @returns {*[]}
	 * @private
	*/
	_rotatePoint(x, y, centerX, centerY, degrees) {
		let newX = (x - centerX) * Math.cos(degrees * Math.PI / 180) - (y - centerY) * Math.sin(degrees * Math.PI / 180) + centerX;
		let newY = (x - centerX) * Math.sin(degrees * Math.PI / 180) + (y - centerY) * Math.cos(degrees * Math.PI / 180) + centerY;
		return [newX, newY];
	},

	/**
     *
     * @param {*} px 手指按下去的坐标
     * @param {*} py 手指按下去的坐标
     * @param {*} x 手指移动到的坐标
     * @param {*} y 手指移动到的坐标
     * @param {*} currentGraph 当前图层的信息
	*/
	transform(px, py, x, y, currentGraph, scale) {
		this.centerX = this.x + this.w / 2;
		this.centerY = this.y + this.h / 2;
		
		this.ctx.translate(px, py);
		
		if (this.type === 'image') {
			const lineA = Math.sqrt(Math.pow(this.centerX - px, 2) + Math.pow(this.centerY - py, 2));
			const lineB = Math.sqrt(Math.pow(this.centerX - x, 2) + Math.pow(this.centerY - y, 2));
			let resize_rito = lineB / lineA;
			
			let new_w = currentGraph.w * scale;
			let new_h = currentGraph.h * scale;

			this.w = new_w;
			this.h = new_h;
			this.x = currentGraph.x - (new_w - currentGraph.w) / 2;
			this.y = currentGraph.y - (new_h - currentGraph.h) / 2;
			this.ctx.translate(-px, -py);
		}
	},

	toPx(rpx) {
		return rpx * this.factor;
	}
};

export default dragGraph;